<?php

namespace Biz\model\activity;



use Biz\service\wiki\Wiki;

class PageModuleWiki extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'page_module_wiki';


    const STATUS_NORMAL = 1;
    const STATUS_DELETE = 9;


    public static function insertModuleWiki($data)
    {
        $data['status'] = self::STATUS_NORMAL;
        $data['addtime'] = date("Y-m-d H:i:s");
        if (self::insert($data)->rowcount()) {
            return self::id();
        } else {
            return false;
        }
    }

    public static function addModuleWiki($pageId, $moduleId, $wikiIds)
    {
        foreach ($wikiIds as $wikiId) {
            $data = [
                'page_id' => $pageId,
                'module_id' => $moduleId,
                'wiki_id' => $wikiId,
                'status' => self::STATUS_NORMAL,
                'addtime' => date('Y-m-d H:i:s')
            ];
            self::insert($data);
        }
        return true;
    }

    public static function updateModuleWiki($wikiId, $data)
    {
        $ret = self::update($data, ['id' => $wikiId]);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function saveModuleWikiSort($sortInfo)
    {
        foreach ($sortInfo as $wikiId => $sort) {
            self::update(['sort' => $sort], ['id' => $wikiId]);
        }
    }

    public static function getWikiByModuleId($moduleId, $format = true)
    {
        $moduleWiki = self::select("*",
            [
                'AND' => [
                    'module_id' => $moduleId,
                    'status' => self::STATUS_NORMAL
                ],
                'ORDER' => [
                    'sort',
                    'id'
                ]
            ]);
        return $format ? self::formatWiki($moduleWiki) : $moduleWiki;
    }

    private static function formatWiki($moduleWiki)
    {
        $wikiIds = array_column($moduleWiki, 'wiki_id');
        $wikiInfos = Wiki::getWikiBaseInfos($wikiIds);
        foreach ($moduleWiki as &$wiki) {
            if (isset($wikiInfos[$wiki['wiki_id']])) {
                $wiki['wiki_info'] = $wikiInfos[$wiki['wiki_id']];
            }
        }
        return $moduleWiki;
    }

    public static function chageWikiStatusById($id, $status)
    {
        if (self::update(['status' => $status], ["id" => $id])->rowcount()) {
            return $id;
        }
    }
}